package com.factory.test.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.yt.serial.EnDeCrypt;


/**
 * 灰度测试View
 */
public class GrayscaleView extends View {

    private Context context;
    private boolean reverse = false;

    public GrayscaleView(Context context) {
        super(context);
        init(context);
    }

    public GrayscaleView(Context context, boolean reverse) {
        super(context);
        this.reverse = reverse;
        init(context);
    }

    public GrayscaleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public GrayscaleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public GrayscaleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }


    private Paint[] paints;
    private int count = 16;
    private int widthPixel;
    private int heightPixel;
    private int mode;


    private void init(Context context){
        this.context = context;
        DisplayMetrics outMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(outMetrics);
        widthPixel = outMetrics.widthPixels;
        heightPixel = outMetrics.heightPixels;

        paints = new Paint[this.count];
        for (int i = 0; i < count; i++) {
            paints[i] = new Paint();
            paints[i].setColor(Color.parseColor("#" + EnDeCrypt.TenToHex(255 / count * i, 2) + "" + EnDeCrypt.TenToHex(255 / count * i, 2) + "" + EnDeCrypt.TenToHex(255 / count * i, 2)));
        }
        mode = heightPixel % count;
        if(reverse){
            reverseArray();
        }
    }

    public void reverseArray(){
        for (int i = 0; i <= paints.length / 2 - 1; i++) {
            Paint temp1 = paints[i];
            Paint temp2 = paints[paints.length - i - 1];
            paints[i] = temp2;
            paints[paints.length - i - 1] = temp1;
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        for (int i = 0; i < count; i++) {
            if(mode > 0){
                canvas.drawRect(0, heightPixel / count * i, widthPixel, heightPixel / count * (i + 1) + mode, paints[i]);
            }else {
                canvas.drawRect(0, heightPixel / count * i, widthPixel, heightPixel / count * (i + 1), paints[i]);
            }
        }
    }
}
